package com.exemplo.flickrsocial.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.http.AndroidHttpClient;
import android.util.Log;

import com.exemplo.flickrsocial.images.FlushedInputStream;
import com.exemplo.flickrsocial.service.ImageDownloadTask;

public final class ImageUtils {

	private static Map<String, SoftReference<Bitmap>> imageCache = new ConcurrentHashMap<String, SoftReference<Bitmap>>(
			20);

	/**
	 * This method must be called in a thread other than UI.
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap downloadImage(String url) {

		// AndroidHttpClient is not allowed to be used from the main thread
		final HttpClient client = AndroidHttpClient.newInstance("Android");
		final HttpGet getRequest = new HttpGet(url);

		try {
			HttpResponse response = client.execute(getRequest);
			final int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				Log.w("ImageDownloader", "Error " + statusCode
						+ " while retrieving bitmap from " + url);
				return null;
			}

			final HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream inputStream = null;
				try {
					inputStream = entity.getContent();

					return BitmapFactory.decodeStream(new FlushedInputStream(
							inputStream));

				} finally {
					if (inputStream != null) {
						inputStream.close();
					}
					entity.consumeContent();
				}
			}
		} catch (IOException e) {
			getRequest.abort();
			Log.w(e.toString(), "I/O error while retrieving bitmap from " + url);

		} catch (IllegalStateException e) {
			getRequest.abort();
			Log.w(e.toString(), "Incorrect URL:" + url);

		} catch (Exception e) {
			getRequest.abort();
			Log.w(e.toString(), "Incorrect URL:" + url);

		} finally {

			if ((client instanceof AndroidHttpClient)) {
				((AndroidHttpClient) client).close();
			}
		}
		return null;
	}

	/**
	 * Pint image White
	 * 
	 * @param bitMap
	 * @return
	 */
	public static Bitmap pintBitMap(Bitmap bitMap, int color) {

		for (int y = 0; y < bitMap.getHeight(); y++) {
			for (int x = 0; x < bitMap.getWidth(); x++) {
				bitMap.setPixel(x, y, color);

			}

		}

		return bitMap;
	}

	/**
	 * split image in 4 part.
	 * 
	 * @param picture
	 * @return
	 */
	public static Bitmap[] splitBitmap(Bitmap picture) {

		Bitmap scaledBitmap = Bitmap
				.createScaledBitmap(picture, 240, 240, true);

		Bitmap[] imgs = new Bitmap[4];
		imgs[0] = Bitmap.createBitmap(scaledBitmap, 0, 0, 80, 80);
		imgs[1] = Bitmap.createBitmap(scaledBitmap, 80, 0, 80, 80);
		imgs[2] = Bitmap.createBitmap(scaledBitmap, 160, 0, 80, 80);
		imgs[3] = Bitmap.createBitmap(scaledBitmap, 0, 80, 80, 80);

		return imgs;

	}

	/**
	 * put to bitmap in cache
	 * 
	 * @param url
	 * @param bitmap
	 */
	public static void putToCache(String url, Bitmap bitmap) {
		imageCache.put(url, new SoftReference<Bitmap>(bitmap));
	}

	/**
	 * get cache
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap getFromCache(String url) {
		if (imageCache.containsKey(url)) {
			return imageCache.get(url).get();
		} else {
			return null;
		}
	}

	public static class DownloadedDrawable extends ColorDrawable {

		private WeakReference<ImageDownloadTask> taskRef;

		public DownloadedDrawable(ImageDownloadTask task) {
			taskRef = new WeakReference<ImageDownloadTask>(task);
		}

		public ImageDownloadTask getBitmapDownloaderTask() {
			if (taskRef != null) {
				return taskRef.get();
			} else {
				return null;
			}
		}
	}

}
